<?php

namespace App\Http\Controllers\Admin\AirLine\Base;

use App\Http\Controllers\Controller;
use App\Http\Requests\airline\base\CodeRequest;
use App\Models\airline\base\CodeDetailModel;
use App\Models\airline\base\CodeModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Code extends Controller
{
    use CodeRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $code = $request->input('code', '');
        $company_id = $request->input('company_id', '');
        $status = $request->input('status', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = CodeModel::query()->with(['create_admin', 'company'])->with('detail');

        if($code){
            $query = $query->where('code', $code);
        }

        if($company_id){
            $query = $query->where('company_id', $company_id);
        }

        if($status != ''){
            $query = $query->where('status', $status);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'code' => $item->code,
                'company_id' => $item->company_id,
                'company_name' => $item->company ? $item->company->name : '',
//                'number' => $item->number,
//                'used' => $item->used,
                "detail" => $item->detail->map(function($item) {
                    $res = [
                        'id' => $item->id,
                        'name' => $item->name,
                        'number' => $item->number,
                        'used' => $item->used,
                    ];
                    return $res;
                }),
                'status' => $item->status,
                'status_text' => CodeModel::STATUS[$item->status],
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin ? $item->create_admin->staff->name: '',
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $find = CodeModel::where('code', $params['code'])->first();
        if($find){
            return $this->error('CODE已存在');
        }

        DB::beginTransaction();
        try {
            $model = new CodeModel();
            $model->company_id = $params['company_id'];
            $model->code = $params['code'];
            $model->status = $params['status'] ?? 0;
            $model->created_admin_id = $auth->id;
            $model->save();

            foreach ($params['detail'] as $ban){
                $detail = new CodeDetailModel();
                $detail->code_id = $model->id;
                $detail->name = $ban['name'];
                $detail->number = $ban['number'];
                $detail->save();
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function update(Request $request, $id){
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = CodeModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        if($model->code != $params['code']){
            $find = CodeModel::where('code', $params['code'])->first();
            if($find){
                return $this->error('CODE已存在');
            }
        }

        DB::beginTransaction();
        try {
            $model->company_id = $params['company_id'];
            $model->code = $params['code'];
            $model->status = $params['status'] ?? 0;
            $model->save();

            CodeDetailModel::where('code_id', $id)->delete();

            foreach ($params['detail'] as $ban){
                $detail = new CodeDetailModel();
                $detail->code_id = $model->id;
                $detail->name = $ban['name'];
                $detail->number = $ban['number'];
                $detail->save();
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }


        return $this->success();
    }


    public function delete(int $id){
        $model = CodeModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }
        $model->delete();
        CodeDetailModel::where('code_id', $id)->delete();
        return $this->success();
    }

    public function select()
    {
        $code_id = request()->input('code_id', '');
        $list = CodeDetailModel::query();
        if($code_id){
            $list = $list->where('code_id', $code_id);
        }

        $list = $list->whereNotNull('name')
            ->groupBy('name')
            ->select('name')
            ->get();
        return $this->success($list);
    }


}
